package com.zis.common;

import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletContext;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.ServletContextAware;

import etcomm.SDK.HttpService.HttpServiceWrapper;

/**
 * spring启动时候加载益体康接口验证信息
 * @author wangshen
 *
 */
public class InitDataListener implements InitializingBean, ServletContextAware {
	
	protected transient Logger logger = Logger.getLogger(this.getClass().getName());

	@Override
	public void setServletContext(ServletContext servletContext) {
		logger.info(" >>> 服务器信息："+servletContext.getServerInfo());
		logger.info(" >>> 应用部署位置："+servletContext.getRealPath("/"));
		logger.info(" >>> 初始化数据开始，当前时间：" + DateUtils.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
        try {
        	//读取配置文件
        	Resource resource = new ClassPathResource("/servConfig.properties");
            Properties pro = PropertiesLoaderUtils.loadProperties(resource);
			String url = pro.getProperty("etcomm.server");//serverURL  
	        String account = pro.getProperty("etcomm.entAccount");//用户名 
	        String password = pro.getProperty("etcomm.password");//密码
	        //读取token
	        HttpServiceWrapper hsw = new HttpServiceWrapper(url);
	        GlobalConfig.ETC_TOKEN = hsw.Auth(account,password);
	        if(GlobalConfig.ETC_TOKEN.isEmpty()){
	        	logger.error(" >>> 获取访问令牌失败!请检查HttpService服务地址及访问帐号是否正确!");
	        }
	        logger.info(" >>> 当前token："+GlobalConfig.ETC_TOKEN +" >>> 有效时间12小时 每11小时50分Spring定时任务自动会刷新token");
	        //加载企业信息
	        String entInfo = hsw.GetEntInfo(GlobalConfig.ETC_TOKEN);
	        GlobalConfig.JSON_ENT_INFO = JSONObject.fromObject(entInfo);
	        logger.info(" >>> 当前企业信息："+entInfo);
	        
	        logger.info(hsw.GetData(GlobalConfig.ETC_TOKEN,"","","",false,true,1,500));
	        
//	        logger.info(" >>> 添加设备操作结果: "+hsw.AddDev(GlobalConfig.ETC_TOKEN,"0903081512000249"));
	        
	        logger.info(" >>> 当前企业设备列表: "+hsw.GetDevs(GlobalConfig.ETC_TOKEN));
		} catch (Exception e) {
			logger.error(" >>> 读取servConfig.properties错误，请检查配置是否正确");
			e.printStackTrace();
		}  
		
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		//在这里也可以初始化信息
		
	}

}
